package com.example.my.android;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

public class ParkingUtil extends SQLiteOpenHelper {
    public ParkingUtil(@Nullable Context context) {
        super(context, "parking.data", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "create table parking (" +
                "id INTEGER primary key autoincrement, " +
                "title varchar(100), " +
                "longitude varchar(100), " +
                "latitude varchar(100)" +
                ")";
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public boolean save(Parking parking){
        ContentValues values = new ContentValues();
        values.put("title", parking.getTitle());
        values.put("longitude", parking.getLongitude());
        values.put("latitude", parking.getLatitude());

        SQLiteDatabase db = getWritableDatabase();
        long rowId = db.insert("parking", null, values);
        db.close();

        if(rowId==-1){
            return false;
        }else{
            return true;
        }
    }

    public List<Parking> findList(){
        List<Parking> parkingList = new ArrayList<>();

        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.query("parking", new String[]{"id", "title", "longitude", "latitude"},
                null, null, null, null, "id desc");
        while(cursor.moveToNext()){
            Parking parking = new Parking();
            parking.setId(cursor.getInt(cursor.getColumnIndex("id")));
            parking.setTitle(cursor.getString(cursor.getColumnIndex("title")));
            parking.setLongitude(cursor.getString(cursor.getColumnIndex("longitude")));
            parking.setLatitude(cursor.getString(cursor.getColumnIndex("latitude")));
            parkingList.add(parking);
        }
        cursor.close();
        db.close();

        return parkingList;
    }
}
